//
//  ChannelList.m
//  kankanVideo
//
//  Created by wangbo on 6/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ChannelList.h"
#import "IndexData.h"
#import "MyCoreData.h"
#import "GANTracker.h"


#define kAppIconHeight    30
#define kAppIconWidth     30

@implementation ChannelList
@synthesize mydelegate;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    //_data=[[NSMutableArray alloc]init];
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}
-(void)dealloc{
    mydelegate=nil;
    [super dealloc];
}
-(void)binddata:(NSMutableArray *)data withFlag:(BOOL)theFlag{
    ismyconcerned=!theFlag;
    //NSLog(@"%@",data);
    _data=data;
    if(!ismyconcerned){
        //MyCoreData *mydata=[[MyCoreData alloc]initWithTableName:@"IndexData"];
        NSArray *arr=[[MyCoreData shareInstance]query];
        for (NSMutableArray *tmp in _data) {
            BOOL fg=NO;
            for(int i=0;i<[arr count];i++){
                IndexData *obj=[arr objectAtIndex:i];
                if ([[tmp objectAtIndex:0] isEqualToString:[obj classid]]) {
                    NSLog(@"find the same item");
                    [tmp addObject:@"1"];
                    fg=YES;
                    break;
                }
            }
            if (fg==NO) {
                [tmp addObject:@"0"];
            }
        }
    }else{
        for (NSMutableArray *tmp in _data) {
            [tmp addObject:@"0"];
        }
    }
    NSLog(@"%@",_data);
    [self.tableView reloadData];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    lazyImages = [[MHLazyTableImages alloc] init];
    lazyImages.placeholderImage = [UIImage imageNamed:@"smallback.png"];
    lazyImages.delegate = self;
    lazyImages.tableView=self.tableView;
    //[self.view setFrame:CGRectMake(90, 44, 220, 416)];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (_data) {
        return _data.count;
    }else{
        return 0;
    }
}

-(void)btnTapped:(id)sender{
    UIButton *btn=(UIButton*)sender;
    [btn setEnabled:NO];
    UITableViewCell *cell=(UITableViewCell *)[btn superview];
    int row=[self.tableView indexPathForCell:cell].row;
    NSLog(@"row:%d",row);
    NSLog(@"===================operation=================");
    if(ismyconcerned){
        [mydelegate modifyItem:-1 withParam:[_data objectAtIndex:row]];
        [_data removeObjectAtIndex:row];
        NSLog(@"%@",_data);
        [self.tableView reloadData];
    }else{
        [mydelegate modifyItem:1 withParam:[_data objectAtIndex:row]];
        [btn setImage:[UIImage imageNamed:@"dingyue2_03.png"] forState:UIControlStateNormal];
        NSError *error;
        if (![[GANTracker sharedTracker] trackEvent:@"看看iospad"
                                             action:@"栏目订阅"
                                              label:[[_data objectAtIndex:row]objectAtIndex:1]
                                              value:0
                                          withError:&error]) {
            NSLog(@"error in trackEvent");
            NSLog(@"栏目订阅_%@",[[_data objectAtIndex:row]objectAtIndex:1]);
        }
    }
    NSLog(@"cell_accessory_tapped_complete");
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 61;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //NSLog(@"cellForRow");
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:CGRectMake(140, 10, 25, 25)];
        //[btn setTag:123];
        [btn setImage:[UIImage imageNamed:@"dingyue_03.png"] forState:UIControlStateNormal];        
        [btn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView=btn;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    [lazyImages addLazyImageForCell:cell withIndexPath:indexPath];
    UIButton *btn=(UIButton*)cell.accessoryView;
    [btn setEnabled:YES];
    [cell.accessoryView setHidden:NO];
    if(ismyconcerned){
        [btn setImage:[UIImage imageNamed:@"dingyue_00.png"] forState:UIControlStateNormal];
    }else{
        [btn setImage:[UIImage imageNamed:@"dingyue1_06.png"] forState:UIControlStateNormal];
        if ([[[_data objectAtIndex:indexPath.row]objectAtIndex:6] isEqualToString:@"1"]) {
            [btn setEnabled:NO];
            [btn setImage:[UIImage imageNamed:@"dingyue2_03.png"] forState:UIControlStateNormal];
        }
    }
    //NSLog(@"row_isgood:%@",[[_data objectAtIndex:indexPath.row]objectAtIndex:4]);
    if (![[[_data objectAtIndex:indexPath.row]objectAtIndex:5] isEqualToString:@"0"]) {
        [cell.accessoryView setHidden:YES];
    }
    // Configure the cell...
    cell.textLabel.text=[[_data objectAtIndex:indexPath.row]objectAtIndex:1];
    cell.textLabel.font=[UIFont fontWithName:@"Arial" size:13];
    //NSLog(@"cell_complete");
    return cell;
}

#pragma mark -
#pragma mark UIScrollViewDelegate

- (void)scrollViewDidEndDragging:(UIScrollView*)scrollView willDecelerate:(BOOL)decelerate
{
	[lazyImages scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView
{
	[lazyImages scrollViewDidEndDecelerating:scrollView];
}

#pragma mark -
#pragma mark MHLazyTableImagesDelegate

- (NSURL*)lazyImageURLForIndexPath:(NSIndexPath*)indexPath
{
    NSLog(@"lazyimage_for_index");
	//AppRecord* appRecord = [self.entries objectAtIndex:indexPath.row];
	return [NSURL URLWithString:[[_data objectAtIndex:indexPath.row] objectAtIndex:2]];
}

- (UIImage*)postProcessLazyImage:(UIImage*)image forIndexPath:(NSIndexPath*)indexPath
{
    if (image.size.width != kAppIconWidth && image.size.height != kAppIconHeight)
	{
        CGSize itemSize = CGSizeMake(kAppIconWidth, kAppIconHeight);
		UIGraphicsBeginImageContextWithOptions(itemSize, YES, 0);
		CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
		[image drawInRect:imageRect];
		UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
		UIGraphicsEndImageContext();
        //[self.tableView reloadData];
		return newImage;
    }
    else
    {
        return image;
    }
}


@end
